local desc_hx_1v3 = [[
  # 虎牢关2022简介
  ______________________

  对在2022年昙花一现于十周年服的变种虎牢关模式进行了魔改，原名是“三英战吕布”，还是熟悉的二、三、四号位选择武将作为联军，一号位固定为“吕布”，不同的是所有玩家都有当“吕布”的机会。“吕布”将以下面的吕布作为副将，体力固定为10，信息如下：

  ## 注意，本模式为PVP模式！（开启双将为“吕布”将获得神秘增益且联军无增益）

  性别：男     体力：10/10      势力：群     初始手牌：8

  技能：

  霸关：锁定技，你的延时类锦囊一定判定失败，你不会被翻面。你的摸牌阶段额外摸3张牌。

  武威：你使用【杀】或【决斗】可以额外指定两个目标。你的出牌阶段可以多使用两张【杀】。

  惊虎：锁定技，你对一名其他角色造成伤害后令其失去1点体力。

  健驹：锁定技，你与其他角色的距离视为1。第三轮你的回合结束后，撤离战场。

  ## 显而易见，三轮后游戏就会结束。

  ## 核心玩法介绍如下：

  联军阵亡时若仍有联军在场则改为休整一轮。

  ## 吕布胜利条件：

  使三名联军同时处于休整状态。或联军累计阵亡5次。

  ## 联军胜利条件：

  三轮内击败吕布。联军一回合内未全部处于休整状态，且累计阵亡次数未达到5次。
]]

local U = require "packages/utility/utility"


local hx_1v3_getLogic = function()
  local hx_1v3_logic = GameLogic:subclass("hx_1v3_logic")

  function GameLogic:prepareForStart()
    local room = self.room
    local players = room.players
    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  function hx_1v3_logic:action()
    self:trigger(fk.GamePrepared)
    local room = self.room
    room:setTag("SkipNormalDeathProcess", true)
    self:attachSkillToPlayers()

    self:prepareDrawPile()

    GameEvent.DrawInitial:create():exec()

    while true do
      GameEvent.Round:create():exec()
      if room.game_finished then break end
      if table.every(room.players, function(p) return p.dead and p.rest == 0 end) then room:gameOver("") end
      room:setCurrent(room.players[1])
    end
  end

  function hx_1v3_logic:prepareDrawPile()
    local room = self.room
    local allCardIds = Fk:getAllCardIds()
    local filterCardIds = {}
    --卡牌白名单
    local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(white_cards, card.package.name) then
          table.removeOne(allCardIds, id)
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        end
        if table.contains(white_cards, card.package.name) then
          if not card.is_derived then
            table.insert(filterCardIds, id)
          end
        end
      end
    end
    local seed = math.random(2 << 32 - 1)
    table.shuffle(filterCardIds, seed)
    room.draw_pile = filterCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)
  end

  function hx_1v3_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local choices = {"当联军！","抢吕布！"}
    local result = U.askForJointChoice(room.players, choices,"","请选择你的身份（选择“抢吕布！”的玩家中的随机一名玩家将成为吕布）",true)
    local lvbus = {}
    for _, p in ipairs(room.players) do
      if result[p.id] == "抢吕布！" then
        table.insert(lvbus, p)
      end
    end
    if #lvbus > 0 then
      local chosen_lord = lvbus[math.random(#lvbus)]
      room:setPlayerProperty(chosen_lord, "role", "lord")
      table.removeOne(lvbus, chosen_lord)
    end
    for _, p in ipairs(lvbus) do
      room:setPlayerProperty(p, "role", "rebel")
    end
    for _, p in ipairs(room.players) do
      if p.role ~= "lord" then
        room:setPlayerProperty(p, "role", "rebel")
      end
    end
  end

  function hx_1v3_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    room:setBanner("@[:]huixiangmode_rule","hx_1v3-intro")

    local lord = room:getLord()
    room:setCurrent(lord)
    local players = room.players
    local nonlord = room:getOtherPlayers(lord)
    -- 1号位多发两个武将
    local generals = room:getNGenerals(#players * generalNum + 2)

    local req = Request:new(players, "AskForGeneral")
    for i, p in ipairs(players) do
      local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      if p.role == "lord" then
        local count = #generals
        table.insert(arg, generals[count])
        table.insert(arg, generals[count - 1])
      end
      req:setData(p, { arg, 1 })
      req:setDefaultReply(p, { arg[1] })
    end
    req:ask()

    local selected = {}
    for _, p in ipairs(players) do
      local general_ret
      general_ret = req:getResult(p)[1]
      room:setPlayerGeneral(p, general_ret, true, true)
      table.insertIfNeed(selected, general_ret)
    end
    generals = table.filter(generals, function(g) return not table.contains(selected, g) end)
    room:returnToGeneralPile(generals)

    for _, g in ipairs(selected) do
      room:findGeneral(g)
    end
    room:askForChooseKingdom(players)

    for _, p in ipairs(players) do
      room:broadcastProperty(p, "general")
    end
    for _, p in ipairs(nonlord) do
      for _, p2 in ipairs(nonlord) do
        if p ~= p2 then
          p:addBuddy(p2)
        end
      end
    end

    room:setTag("SkipNormalDeathProcess", true)
  end

  function hx_1v3_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
    local n = room.settings.enableDeputy and 2 or 1
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill.lordSkill then
        return
      end
      if #skill.attachedKingdom > 0 and not table.contains(skill.attachedKingdom, player.kingdom) then
        return
      end
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      if p.role == "lord" then
          room:changeHero(p, "sy__lvbu", false, true, true, false, false)
          if n == 2 then
            room:handleAddLoseSkills(p, "huixiang__fenghuo", nil, false)
          end
      end
    end
  end
  return hx_1v3_logic
end

local hx_1v3_rule = fk.CreateTriggerSkill{
  name = "#hx_1v3_rule",
  priority = 0.001,
  mute = true,
  events = {fk.Death,fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    if event == fk.GameStart then
      return true
    elseif event == fk.Death then
      return player.role ~= "lord" and player.dead and player.rest == 0
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = room.settings.enableDeputy and 2 or 1
    if event == fk.Death then
      room:addPlayerMark(room:getLord(), "@huixiangmode_dead", 1)
      player._splayer:setDied(false)
      room:setPlayerRest(player, 1)
      local onlyLvbu = #room:getOtherPlayers(room:getLord()) == 0
      if onlyLvbu or room:getLord():getMark("@huixiangmode_dead") >= 5 then
        room:gameOver("lord")
      end
    end
    if event == fk.GameStart and room:getLord():getMark("huixiangmode_sound") == 0 then
      room:broadcastPlaySound("./packages/huixiang/audio/skill/kaiju2022")
      room:delay(8000)
      room:addPlayerMark(room:getLord(),"huixiangmode_sound", 1)
    end
  end,
}
Fk:addSkill(hx_1v3_rule)

local hx_1v3_mode = fk.CreateGameMode{
  name = "hx_1v3_mode",
  minPlayer = 4,
  maxPlayer = 4,
  rule = hx_1v3_rule,
  logic = hx_1v3_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 1 min", passed = playedTime >= 60 },
    { text = "2v2: left you alive", passed = not table.find(Fk:currentRoom().players, function(p)
      return p ~= Self and p.role == Self.role and not (p.dead and p.rest == 0)
    end) } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p) ---@type Player[]
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
  get_adjusted = function (self, player)
    if player.role == "lord" then
      return {hp = 10, maxHp = 10}
    end
    return {}
  end
}

Fk:loadTranslationTable{
  ["hx_1v3_mode"] = "虎牢关2022",
  ["#hx_1v3_rule"] = "虎牢关2022规则",
  ["@huixiangmode_dead"] = "联军阵亡次数",
  ["@[:]huixiangmode_rule"]="模式",
  ["hx_1v3-intro"] = "虎牢关2022",
  [":hx_1v3-intro"] = [[
  注意，本模式为PVP模式！
  <br><br>（开启双将“吕布”将获得神秘增益）
  <br><br>联军阵亡时若仍有联军在场则改为休整一轮。
  <br><br>吕布胜利条件：
  使三名联军同时处于休整状态。或联军累计阵亡5次。
  <br><br>联军胜利条件：
  击败吕布。联军一回合内未全部处于休整状态，且累计阵亡次数未达到5次。]],
  [":hx_1v3_mode"] = desc_hx_1v3,
}

return hx_1v3_mode
